import React,{ useState, useEffect } from 'react';
import {
  ScanOutlined,
  PoweroffOutlined,
  ReloadOutlined,
  SoundOutlined,
  AlertOutlined,
  ToTopOutlined,
  DeleteOutlined
} from '@ant-design/icons';
import { Modal, Tabs ,Row, Col, Button, Slider, InputNumber, Checkbox, TimePicker, Select,message, Image, Spin, Form } from 'antd';
import { DeviceListItem } from '../data';
import { FormInstance } from 'antd/lib/form';
import moment from 'moment';
import {
  devicePropForControl, 
  deviceControlForTimerSwitch,
  deviceControlForPrintScreen,
  deviceControlForReboot,
  deviceControlForVolume,
  deviceControlForBackLight,
  deviceControlForSystemUpgrade,
  deviceControlForCleanCache
} from '../service'
import styles from '../index.less';

interface CreateFormProps {
  modalVisible: boolean;
  onCancel: () => void;
  values:DeviceListItem;
}

const { TabPane } = Tabs;
const { RangePicker } = TimePicker;
const { Option } = Select;

// const weekOptions = [
//   { label: '周一', value: 1 },
//   { label: '周二', value: 2 },
//   { label: '周三', value: 3 },
//   { label: '周四', value: 4 },
//   { label: '周五', value: 5 },
//   { label: '周六', value: 6 },
//   { label: '周日', value: 7 },
// ];

// const initLocalDate = () =>{
//   let array = [];
//   for(var i = 1; i<=31;i++){
//     array.push(i);
//   }
//   return array;
// }
let formObj = new Object();
let powerOnTime = "00:00:00";
let powerOffTime = "00:00:00";

const fallback = '';

const DeviceControl: React.FC<CreateFormProps> = (props) => {
  const { modalVisible, onCancel, values } = props;
  const [loading, setLoading] = useState<boolean>(false);
  const [deviceValue, setDeviceValue] = useState<DeviceListItem>();
  const [src, setSrc] = useState<string>(fallback);
  const [screenLoading, setScreenLoading] = useState<boolean>(false);
  const [timerSwitchLoading, setTimerSwitchLoading] = useState<boolean>(false);
  const [rebootLoading, setRebootLoading] = useState<boolean>(false);
  const [updateLoading, setUpdateLoading] = useState<boolean>(false);
  const [clearLoading, setClearLoading] = useState<boolean>(false);
  const [voice, setVoice] = useState<number>(0);
  const [light, setLight] = useState<number>(0);
  const [lightDisabled, setLightDisabled] = useState<boolean>(false);


  const [controlDisabled, handleControlDisabled] = useState<boolean>(false);
  const [cycle, setCycle] = useState<string>("day");
  const [daysList, setDaysList] = useState([]);
  const formRef = React.createRef<FormInstance>();


  
  useEffect(() => {
    if(modalVisible){
      setLoading(true);
      setSrc(fallback);
      new Promise((resolve, reject) => {
        devicePropForControl(values.id)
          .then((res) => {
            setLoading(false);
            if (res && res.code === 200) {
              const data = res.data;
              values["currentApkVersion"] = data.currentApkVersion;
              values["latestApkVersion"] = data.latestApkVersion;
              values["newestVersionId"] = data.newestVersionId;
              values["runningHours"] = data.runningHours;
              const backlightAutoEnable = data.backlightAutoEnable;//自动背光
              values["backlightAutoEnable"] = backlightAutoEnable;
              setLightDisabled(backlightAutoEnable);
              const timePowerOnDatetime = data.timePowerOnDatetime;
              const timePowerOffDatetime = data.timePowerOffDatetime;
              formObj["startTime"] = [moment(timePowerOnDatetime?timePowerOnDatetime:"00:00:00", 'HH:mm:ss'), moment(timePowerOffDatetime?timePowerOffDatetime:"00:00:00", 'HH:mm:ss')]
              values["timePowerConfig"] = data.timePowerConfig?.split(",").map(Number);
              const timePower = data.timePowerEnable;
              if(timePower){//定时开关机

                const type = data.timePowerConfig.split(",");
                if(type.length === 7){
                  setCycle("day");
                }else{
                  setCycle("week");
                }
              }else{//不定时
                formObj["startTime"] = [moment(powerOnTime, 'HH:mm:ss'), moment(powerOffTime, 'HH:mm:ss')]
                values["timePowerConfig"] = [];
                setCycle("day");
              }
              handleControlDisabled(timePower);
              
              if(data.deviceVolume){
                setVoice(parseInt(data.deviceVolume));
              }else{
                setVoice(1);
              }
              if(data.backlightCurrentValue){
                setLight(data.backlightCurrentValue);
              }else{
                setLight(1);
              }
              setDeviceValue(values);
              resolve(true);
            }else {
              message.error('获取失败，'+res.message);
              resolve(false);
            }
          })
          .catch((error) => {
            message.error('请求失败');
            reject(error);
          });
      });
    }else{
      setLoading(false);
    }
},[modalVisible]);

  function callback(key) {
    // console.log(key);
  }

  const onOpenChange =(e:Event) =>{
    handleControlDisabled(e.target.checked);
    if(!e.target.checked){
      setCycle("day");
    }
  }

  // const onAutoChange = (e:Event) =>{
  //   if(e.target.checked){
  //     setLightDisabled(true);
  //   }else{
  //     setLightDisabled(false);
  //   }
  //   deviceControlForLightCommand(!lightDisabled);
  // }

  const rangePickerChange = (value:any,dateString:string) => { //计划日期
    if(dateString){
      powerOnTime = dateString[0];
      powerOffTime = dateString[1];
    }
  }


  const weekSelectChange = (week:any) => {
    formRef.current?.validateFields();
    setDaysList(week)
  }

  // const dateSelectChange = (id:string) =>{
  //   const selectedList = daysList.concat();//深拷贝数组，再重新复制，可触发更新，直接复制不会触发，因为浅拷贝
  //   let index = selectedList.indexOf(id);
  //   if(index > -1){
  //     selectedList.splice(index,1);
  //   }else{
  //     selectedList.push(id);
  //   }
  //   setDaysList(selectedList);
  //   formRef.current?.setFieldsValue({month:selectedList});
  //   formRef.current?.validateFields();
  // }
  //音量控制请求
  const deviceControlForVolumeCommand = () =>{
    const mac = values.mac;
    const param = new Object;
    param["volume"] = voice;
    setLoading(true);
    new Promise((resolve, reject) => {
      deviceControlForVolume(mac,param)
        .then((res) => {
          setLoading(false);
          if (res.code === 200) {
            resolve(true);
          }else {
            message.error("设置失败，"+res.message);
            resolve(false);
          }
        })
        .catch((error) => {
          setLoading(false);
          reject(error);
        });
    });
  }

  //音量控制
  const onVoiceChange = (value:number) => {
    setVoice(value);
  };

  // const deviceControlForLightCommand1 = () =>{
  //   deviceControlForLightCommand(false);
  // }

  //亮度控制
  const deviceControlForLightCommand = () =>{
    const mac = values.mac;
    const param = new Object;
    param["auto"] = false;
    param["backLight"] = light;
    setLoading(true);
    new Promise((resolve, reject) => {
      deviceControlForBackLight(mac,param)
        .then((res) => {
          setLoading(false);
          if(res){
            if (res.code === 200) {
              resolve(true);
            }else {
              message.error("设置失败，"+res.message);
              resolve(false);
            }
          }
        })
        .catch((error) => {
          setLoading(false);
          reject(error);
        });
    });
  }
  const onLightChange = (value:number) => {
    setLight(value);
  };
  //设备截屏
  const deviceControlForPrintScreenCommand = () => {
    const mac = values.mac;
    setScreenLoading(true);
    new Promise((resolve, reject) => {
      deviceControlForPrintScreen(mac)
        .then((res) => {
          setScreenLoading(false);
          if (res && res.code === 200) {
            message.success('截屏成功');
            setSrc(res.data);
            console.log(res.data)
            resolve(true);
          }else {
            message.error('截屏失败，通讯异常');
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('请求失败');
          setScreenLoading(false);
          reject(error);
        });
    });
  }
  //重启设备
  const deviceControlForRebootCommand = () => {
    const mac = values.mac;
    setRebootLoading(true);
    new Promise((resolve, reject) => {
      deviceControlForReboot(mac)
        .then((res) => {
          setRebootLoading(false);
          if (res.code === 200) {
            message.success('重启成功');
            resolve(true);
          }else {
            message.error('重启失败，'+res.message);
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('请求失败');
          setRebootLoading(false);
          reject(error);
        });
    });
  }
  //设备升级
  const deviceControlForSystemUpgradeCommand = () => {
    const mac = values.mac;
    const param = new Object;
    param["apkVersionId"] = values?.latestApkVersion.id;
    setUpdateLoading(true);
    new Promise((resolve, reject) => {
      deviceControlForSystemUpgrade(mac,param)
        .then((res) => {
          setUpdateLoading(false);
          if (res.code === 200) {
            message.success('发送成功');
            resolve(true);
          }else {
            message.error('发送失败，'+res.message);
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('请求失败');
          setUpdateLoading(false);
          reject(error);
        });
    });
  }
  //清除缓存
  const deviceControlForCleanCacheCommand = () => {
    const mac = values.mac;
    setClearLoading(true);
    new Promise((resolve, reject) => {
      deviceControlForCleanCache(mac)
        .then((res) => {
          setClearLoading(false);
          if (res.code === 200) {
            message.success('清除成功');
            resolve(true);
          }else {
            message.error('清除失败，'+res.message);
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('请求失败');
          setClearLoading(false);
          reject(error);
        });
    });
  }

  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 10 },
  };
  const tailLayout = {
    wrapperCol: { offset: 4, span: 10 },
  };

  

  const onTypeChange = (type:string) =>{ //循环周期select
      setCycle(type);
      setDaysList([]);
      if(type == "day"){
        // formRef.current?.setFieldsValue({month:[],week:[]});
        formRef.current?.setFieldsValue({week:[]});
      }
      // else if( type == "week"){
      //   formRef.current?.setFieldsValue({month:[]});
      // }else if(type =="month"){
      //   formRef.current?.setFieldsValue({week:[]});
      // }
  }

  //定时开关机
  const onFinish = () => {
    const mac = values.mac;
    const obj = new Object;
    if(cycle === "day"){
      obj["days"] = [1,2,3,4,5,6,7];
    }else{
      obj["days"] = daysList;
    }
    obj["enable"] = controlDisabled;//是否启用
    obj["powerOnTime"] = powerOnTime;
    obj["powerOffTime"] = powerOffTime;
    setTimerSwitchLoading(true);
    new Promise((resolve, reject) => {
      deviceControlForTimerSwitch(mac,obj)
        .then((res) => {
          setTimerSwitchLoading(false);
          if (res.code === 200) {
            message.success('设置成功');
            resolve(true);
          }else {
            message.error('设置失败，'+res.message);
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('请求失败');
          setTimerSwitchLoading(false);
          reject(error);
        });
    });
  }

  const renderContent = () => {
    return (
      <>
        <Tabs onChange={callback} type="card" className={styles.deviceDetail}>
            <TabPane tab={<span><ScanOutlined />屏幕截图</span>} key="1">
              <Button 
                type="primary" 
                style={{verticalAlign:"bottom",marginRight:5}} 
                loading={screenLoading}
                onClick={deviceControlForPrintScreenCommand}>
                  <ScanOutlined />
                  开始截屏
              </Button>
              <span style={{fontSize:12,color:"#ff4d4f"}}>*点击【开始截屏】按钮，截取当前屏幕画面</span>
              <Image
                width={200}
                style={{display:"block",margin:"10px 0"}}
                src={src}
                // preview={false}
                // fallback={fallback}
              />
            </TabPane>
            <TabPane tab={<span><PoweroffOutlined />定时开关机</span>} key="2">
                  <Row>
                  <Col span={24}>
                    <Checkbox defaultChecked={controlDisabled} onChange={onOpenChange}>定时开关机</Checkbox>
                  </Col>
                </Row>
                <Form 
                  {...layout} 
                  ref={formRef} 
                  onFinish={onFinish} 
                  initialValues={formObj}
                >
                <Form.Item 
                  name="startTime" 
                  label="开关机时间" 
                  rules={[{ required: controlDisabled }]}>
                  <RangePicker 
                      placeholder={["开机时间","关机时间"]}
                      style={{verticalAlign:"bottom",marginRight:5}} 
                      disabled={!controlDisabled}
                      onChange={rangePickerChange}
                    />
                </Form.Item>
                <Form.Item 
                name="type" 
                label="周期" 
                initialValue={cycle}
                rules={[{ required: controlDisabled }, {
                    validator: (rule, value, callback) => {
                      if(value === "week" && 
                        (formRef.current?.getFieldValue('week') == undefined
                        || formRef.current?.getFieldValue('week').length == 0)
                      ){
                          callback("请选择循环周期");
                      }
                      // else if(value === "month" && 
                      //   (formRef.current?.getFieldValue('month') == undefined
                      //   || formRef.current?.getFieldValue('month').length == 0)
                      // ){
                      //     callback("请选择循环周期");
                      // }
                      else{
                        callback();
                      }
                    },
                },]}>
                <Select defaultValue="day"  onChange={onTypeChange} style={{width:200}} disabled={!controlDisabled}>
                  <Option value="day">每天</Option>
                  {/* <Option value="week">每周</Option> */}
                  {/* <Option value="month">每月</Option> */}
                </Select>
              </Form.Item>
              {/* <Form.Item
                  noStyle
                  shouldUpdate={(prevValues, currentValues) =>
                  prevValues.type !== currentValues.type
                  }   
              >
              {({ getFieldValue }) => {
                  return cycle === "week" && controlDisabled? (
                  <Form.Item 
                    label=" " 
                    colon={false} name="week" 
                    initialValue={(values?.timePowerConfig.length > 0)?values.timePowerConfig:[]}
                  >
                      <Checkbox.Group options={weekOptions} onChange={weekSelectChange} />
                  </Form.Item>
                  ) : null;
              }}
              </Form.Item> */}
              {/* <Form.Item hidden={true} name="month">
              </Form.Item>
              <Form.Item
                  {...tailLayout}
                  noStyle
                  shouldUpdate={(prevValues, currentValues) =>
                  prevValues.type !== currentValues.type
                  }   
              >
              {({ getFieldValue }) => {
                  return cycle === "month" ? (
                  <Form.Item label=" "  colon={false}>
                      <div className={styles.calendarList} style={{width:200}}>
                        <ul>
                          {initLocalDate().map((item,index) => 
                            <li key={item} className={daysList.indexOf(item)>-1 ? "selected":""} onClick={()=> dateSelectChange(item)}><span>{item}</span></li>
                          )} 
                        </ul>
                      </div>
                  </Form.Item>
                  ) : null;
              }}
              </Form.Item> */}
                <Form.Item {...tailLayout}>
                  <Button type="primary" loading={timerSwitchLoading} htmlType="submit">
                    <PoweroffOutlined />保存
                  </Button>
                </Form.Item>
              </Form>
            </TabPane>
            <TabPane tab={<span><ReloadOutlined />重启系统</span>} key="3" style={{textAlign:"center"}}>
              <span style={{display:"block", margin:"10px 0 30px"}}>当前设备已运行{deviceValue?.runningHours}小时，是否立刻重启？</span>
              <Button 
                type="primary" 
                loading={rebootLoading}
                onClick={deviceControlForRebootCommand}
              >
                <ReloadOutlined />立即重启
              </Button>
            </TabPane>
            <TabPane tab={<span><SoundOutlined />音量控制</span>} key="4">
              <span>调节音量<SoundOutlined style={{marginLeft:3}}/></span>
              <Row>
                <Col span={12}>
                  <Slider
                    min={1}
                    max={100}
                    onChange={onVoiceChange}
                    onAfterChange={deviceControlForVolumeCommand}
                    value={typeof voice === 'number' ? voice : 0}
                  />
                </Col>
                <Col span={12}>
                  <InputNumber
                    min={1}
                    max={100}
                    style={{ margin: '0 5px 0 16px',verticalAlign:"bottom"  }}
                    value={voice}
                    onChange={onVoiceChange}
                    onPressEnter={deviceControlForVolumeCommand}
                  />
                  <span style={{fontSize:12,color:"#ff4d4f"}}>输入框按下回车键进行设置</span>
                </Col>
              </Row>
            </TabPane>
            <TabPane tab={<span> <AlertOutlined />亮度控制</span>} key="5">
              {/* <Checkbox onChange={onAutoChange} defaultChecked={values?.backlightAutoEnable}>自动背光</Checkbox> */}
              <span>调节亮度<AlertOutlined style={{marginLeft:3}}/></span>
              <Row>
                <Col span={12}>
                  <Slider
                    // disabled={lightDisabled}
                    min={1}
                    max={100}
                    onChange={onLightChange}
                    onAfterChange={deviceControlForLightCommand}
                    value={typeof light === 'number' ? light : 0}
                  />
                </Col>
                <Col span={12}>
                  <InputNumber
                    // disabled={lightDisabled}
                    min={1}
                    max={100}
                    style={{ margin: '0 5px 0 16px',verticalAlign:"bottom" }}
                    value={light}
                    onChange={onLightChange}
                    onPressEnter={deviceControlForLightCommand}
                  />
                  <span style={{fontSize:12,color:"#ff4d4f"}}>输入框按下回车键进行设置</span>
                </Col>
              </Row>
            </TabPane>
            <TabPane tab={<span> <ToTopOutlined />系统升级</span>} key="6" style={{textAlign:"center"}}>
              <span style={{display:"block", margin:"10px 0"}}>当前版本为： 
                <span style={{color:"#1890ff"}}>{deviceValue?.currentApkVersion?deviceValue.currentApkVersion.versionNo:"--"}</span>，检测到最新版本为： 
                <span style={{color:"#1890ff"}}>{deviceValue?.latestApkVersion?deviceValue.latestApkVersion.versionNo:"--"}</span>
              </span>
              <span style={{display:"block", margin:"10px 0"}}>是否立即升级？</span>
              <Button 
                type="primary"
                disabled={((deviceValue?.currentApkVersion && deviceValue?.latestApkVersion) && 
                (deviceValue?.currentApkVersion.versionNo< deviceValue?.latestApkVersion.versionNo))?false:true }
                loading={updateLoading}
                onClick={deviceControlForSystemUpgradeCommand}
              >
                <ToTopOutlined />立即升级
              </Button>
            </TabPane>
            <TabPane tab={<span><DeleteOutlined />清理缓存</span>} key="7" style={{textAlign:"center"}}>
              <span style={{display:"block", margin:"10px 0"}}>清理缓存后，设备将重新启动，是否立即清理设备缓存？</span>
              <Button 
                type="primary"
                loading={clearLoading}
                onClick={deviceControlForCleanCacheCommand}
              >
                <DeleteOutlined />立即清理
              </Button>
              
            </TabPane>
          </Tabs>
      </>
    );
  };

  return (
    <Modal
      destroyOnClose
      title="远程控制"
      width={830}
      visible={modalVisible}
      onCancel={onCancel}
      footer={[
        <Button type="default" onClick={onCancel}>返回</Button>
      ]}
    >
      <Spin spinning={loading} delay={100}>
        <span style={{display:"block", marginBottom:10}}>当前设备：{deviceValue?.name}</span>
        {renderContent()}
      </Spin>
    </Modal>
  );
};

export default DeviceControl;
